package com.weiweiqin.controller.home;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

import com.weiweiqin.model.*;
import com.weiweiqin.service.*;
import com.weiweiqin.utils.BigDemicalUtil;
import com.weiweiqin.utils.kanjia.PingDuoDuoReduceRule;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.weiweiqin.vo.common.GoodsQueryVO;
import com.weiweiqin.vo.common.Page;
import com.weiweiqin.vo.common.Result;

import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("front/goods")
public class FGoodsController {

	private static final Logger logger = LoggerFactory.getLogger(FGoodsController.class);

	@Autowired
	private GoodsService goodsService;
	
	@Autowired
	private CommentService commentService;

	@Autowired
	private ColorSizeItemService colorSizeItemService;

	@Autowired
	private ColorService colorService;

	@Autowired
	private SizeService sizeService;

    @Autowired
    private CustomerService customerService;

	@Autowired
    private KjGoodsCustomerItemService kjGoodsCustomerItemService;

	@Autowired
	private CustomerFavItemService customerFavItemService;

	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/getBuyInfo.do", method = { RequestMethod.POST,
			RequestMethod.GET })
	@ResponseBody
	public String getBuyInfo(Integer itemId,Integer goodsId, int num, Integer colorId, Integer sizeId, HttpSession session) {
		logger.info("Enter method addCart,goodsId=" + goodsId + ":num=" + num+":colorId="+colorId+":sizeId="+sizeId);
		Result result = new Result();
		//以商品ID、颜色、尺码为key
		Color color = colorService.get(colorId);
		Size size = sizeService.get(sizeId);
		Goods goods = goodsService.get(goodsId);
		ColorSizeItem colorSizeItem = colorSizeItemService.get(itemId);
		double totalPrice = BigDemicalUtil.mul(colorSizeItem.getPrice(), num*100,2);
		Map<String, Object> mp = new HashMap<String, Object>();
		mp.put("color", color.getColor());
		mp.put("colorPic", color.getPic());
		mp.put("size", size.getSize());
		mp.put("goods", goods);
		mp.put("price", colorSizeItem.getPrice());
		mp.put("totalPrice", totalPrice);
		result.setObj(mp);
		result.setResult(true);
		return result.toJson();
	}

	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/addOrUpdateKjGoodsCustomerItem.do", method = { RequestMethod.POST,
			RequestMethod.GET })
	@ResponseBody
	public String addOrUpdateKjGoodsCustomerItem(Integer goodsId,double kjPrice,Integer customerId,HttpSession session) {
		logger.info("Enter method addKjGoodsCustomerItem,goodsId=" + goodsId);
		Result result = new Result();
		Customer customer = (Customer)session.getAttribute("customer");
		String currKPrice = "";
		try {
			KjGoodsCustomerItem kjGoods = null;
			//分享进入
			if(null != customerId) {
				kjGoods = kjGoodsCustomerItemService.getByGoodsIdAndCustomerId(goodsId,customerId);
			//本人进入
			} else {
				kjGoods = kjGoodsCustomerItemService.getByGoodsIdAndCustomerId(goodsId, customer.getId());
			}
			//first save
			if(null == kjGoods) {
				PingDuoDuoReduceRule pingRule = new PingDuoDuoReduceRule(70, 10);
				List<BigDecimal> reduceList = pingRule.getReduceList(new BigDecimal(kjPrice), 20);
				BigDecimal bigDecimal = reduceList.get(0);
				currKPrice = bigDecimal.toString();
				String priceList = StringUtils.join(reduceList, ',');
				KjGoodsCustomerItem kjGoodsCustomerItem = new KjGoodsCustomerItem();
				kjGoodsCustomerItem.setGoodsId(goodsId);
				kjGoodsCustomerItem.setCustomerId(customer.getId());
				kjGoodsCustomerItem.setDaoNum(1);
				kjGoodsCustomerItem.setUpdateDate(new Date());
				kjGoodsCustomerItem.setStatus(1);
				kjGoodsCustomerItem.setPriceList(priceList);
				kjGoodsCustomerItem.setPrice(bigDecimal.doubleValue());
				goodsService.saveOrUpdateKjInfo(kjGoodsCustomerItem,customer.getId(),bigDecimal.doubleValue());
			} else {
				int daoNum = kjGoods.getDaoNum();
				if(daoNum <10) {
					String priceList = kjGoods.getPriceList();
					String[] split = priceList.split(",");
					String priceStr = split[daoNum];
					currKPrice = priceStr;
					double price = kjGoods.getPrice();
					price = price + Double.valueOf(priceStr);
					kjGoods.setPrice(price);
					daoNum++;
					kjGoods.setDaoNum(daoNum);
					goodsService.saveOrUpdateKjInfo(kjGoods,customerId,Double.valueOf(priceStr));
				}else {
					result.setResult(false);
					result.setErrorMsg("已经砍到底价");
					return result.toJson();
				}
			}
		}catch(Exception e) {
			result.setResult(false);
			result.setErrorMsg("服务器错误");
			return result.toJson();
		}
		result.setObj(currKPrice);
		result.setResult(true);
		return result.toJson();
	}
	
	/**
	 * 根据grade查询goods
	 * 
	 * @param goodsQueryVO
	 * @return
	 */
	@RequestMapping(value = "/goodsListByGrade.do", method = {
			RequestMethod.POST, RequestMethod.GET })
	@ResponseBody
	public String goodsListByGrade(GoodsQueryVO goodsQueryVO,HttpSession session) {
		logger.info("Enter method home...");
//        TODO 模拟登录
//        Customer customer = customerService.getByOpenid("obAIa5-9BUmzAOHtNxzewi9wuTQ0");
//        session.setAttribute("customer", customer);
		Customer customerSess = (Customer) session.getAttribute("customer");
		Result result = new Result();
		Page page = new Page();
		if (goodsQueryVO.getPageSize() != null) {
			page.setPageSize(goodsQueryVO.getPageSize());
		}
		page.setCurrPage(goodsQueryVO.getCurrPage());
		Map<String, Object> conditions = new HashMap<String, Object>();
		//满足积分兑换商品
		if(goodsQueryVO.getIsJf() !=null && goodsQueryVO.getIsJf() == 1) {
			Customer customerS = (Customer) session.getAttribute("customer");
			Customer customerData = customerService.get(customerS.getId());
			conditions.put("integral",customerData.getIntegral());
		}
		if (goodsQueryVO.getGrade() != null) {
			conditions.put("grade", goodsQueryVO.getGrade());
		}

		if (goodsQueryVO.getIsKj() != null) {
			conditions.put("isKj", goodsQueryVO.getIsKj());
		}

		if (null != goodsQueryVO.getCategoryId()
				&& goodsQueryVO.getCategoryId() != 0) {
			conditions.put("categoryId", goodsQueryVO.getCategoryId());
		}

		if (null != goodsQueryVO.getBrandsId()
				&& goodsQueryVO.getBrandsId() != 0) {
			conditions.put("brandsId", goodsQueryVO.getBrandsId());
		}

		if (!StringUtils.isEmpty(goodsQueryVO.getTitle())) {
			conditions.put("title", goodsQueryVO.getTitle());
		}
		
		conditions.put("mark",0);
		
		String sortType = goodsQueryVO.getSortType();
		String sortStates = goodsQueryVO.getSortStates();
		if(!StringUtils.isEmpty(sortType) && !StringUtils.isEmpty(sortStates)){
			if("date".equals(sortType)){
				conditions.put("orderBy","a.update_date "+sortStates+" ");
			}else if("price".equals(sortType)){
				conditions.put("orderBy","a.now_price "+sortStates+" ");
			}else if("sale".equals(sortType)){
				conditions.put("orderBy","a.buy_num "+sortStates+" ");
			}
		}

		List<Goods> goodsList = null;
		int totalCount;
		try {
			goodsList = goodsService.pageList(page, conditions);
			if(null != customerSess) {
				for (Goods goods : goodsList) {
					CustomerFavItem isExistFav = customerFavItemService.getByGoodsIdAndCustomerId(customerSess.getId(), goods.getId());
					if(null != isExistFav) {
						goods.setIsFav(1);
					}
				}
			}
			totalCount = goodsService.totalCount(conditions);
		} catch (Exception e) {
			logger.error("数据库异常", e);
			result.setErrorMsg("数据库异常");
			result.setResult(false);
			return result.toJson();
		}
		page.setTotalCount(totalCount);
		Map<String, Object> mp = new HashMap<String, Object>();
		mp.put("totalPage", page.getTotalPage());
		mp.put("totalCount", page.getTotalCount());
		mp.put("goodsList", goodsList);
		result.setObj(mp);
		result.setResult(true);
		return result.toJson();
	}

	/**
	 * 获取客户收藏
	 * @return
	 */
	@RequestMapping(value = "/getFavListByCustomerId.do", method = {
			RequestMethod.POST, RequestMethod.GET })
	@ResponseBody
	public String getFavListByCustomerId(int currPage,HttpSession session) {
		logger.info("Enter method getFavListByCustomerId...");
		Result result = new Result();
		Page page = new Page();
		page.setCurrPage(currPage);
		Map<String, Object> conditions = new HashMap<String, Object>();
		Customer customer = (Customer) session.getAttribute("customer");
		conditions.put("customerId",customer.getId());
		List<Goods> goodsList = new ArrayList<>();
		int totalCount;
		try {
			List<CustomerFavItem> customerFavItems = customerFavItemService.pageList(page, conditions);
			for (CustomerFavItem customerFavItem : customerFavItems) {
				Goods goods = goodsService.get(customerFavItem.getGoodsId());
				goodsList.add(goods);
			}
			totalCount = customerFavItemService.totalCount(conditions);
		} catch (Exception e) {
			logger.error("数据库异常", e);
			result.setErrorMsg("数据库异常");
			result.setResult(false);
			return result.toJson();
		}
		page.setTotalCount(totalCount);
		Map<String, Object> mp = new HashMap<String, Object>();
		mp.put("totalPage", page.getTotalPage());
		mp.put("totalCount", page.getTotalCount());
		mp.put("goodsList", goodsList);
		result.setObj(mp);
		result.setResult(true);
		return result.toJson();
	}

	/**
	 * 客户加入收藏
	 * @return
	 */
	@RequestMapping(value = "/addFav.do", method = {
			RequestMethod.POST, RequestMethod.GET })
	@ResponseBody
	public String addFav(int goodsId,HttpSession session) {
		logger.info("Enter method getFavListByCustomerId...");
		Result result = new Result();
		Customer customer = (Customer) session.getAttribute("customer");
		try {
			CustomerFavItem byGoodsIdAndCustomerId = customerFavItemService.getByGoodsIdAndCustomerId(customer.getId(), goodsId);
			if(null == byGoodsIdAndCustomerId) {
				CustomerFavItem customerFavItem = new CustomerFavItem();
				customerFavItem.setCreateDate(new Date());
				customerFavItem.setCustomerId(customer.getId());
				customerFavItem.setGoodsId(goodsId);
				customerFavItemService.save(customerFavItem);
			}
		} catch (Exception e) {
			logger.error("数据库异常", e);
			result.setErrorMsg("数据库异常");
			result.setResult(false);
			return result.toJson();
		}
		result.setResult(true);
		return result.toJson();
	}

	/**
	 * 客户取消收藏
	 * @return
	 */
	@RequestMapping(value = "/cancelFav.do", method = {
			RequestMethod.POST, RequestMethod.GET })
	@ResponseBody
	public String cancelFav(int goodsId,HttpSession session) {
		logger.info("Enter method getFavListByCustomerId...");
		Result result = new Result();
		Customer customer = (Customer) session.getAttribute("customer");
		try {
			CustomerFavItem customerFavItem = customerFavItemService.getByGoodsIdAndCustomerId(customer.getId(), goodsId);
			customerFavItemService.del(customerFavItem.getId());
		} catch (Exception e) {
			logger.error("数据库异常", e);
			result.setErrorMsg("数据库异常");
			result.setResult(false);
			return result.toJson();
		}
		result.setResult(true);
		return result.toJson();
	}
	
	/**
	 * 根据grade查询goods
	 * @param goodsQueryVO
	 * @return
	 */
	@RequestMapping(value = "/hotList.do", method = { RequestMethod.POST,
			RequestMethod.GET })
	@ResponseBody
	public String hotList(GoodsQueryVO goodsQueryVO) {
		logger.info("Enter method home...");
		Result result = new Result();
		Page page = new Page();
		if(goodsQueryVO.getPageSize() != null){
			page.setPageSize(goodsQueryVO.getPageSize());
		}
		page.setCurrPage(goodsQueryVO.getCurrPage());
		Map<String,Object> conditions = new HashMap<String, Object>();
		if(goodsQueryVO.getGrade() != null){
			conditions.put("grade",goodsQueryVO.getGrade());
		}
		
		if(null != goodsQueryVO.getCategoryId() && goodsQueryVO.getCategoryId() != 0){
			conditions.put("categoryId", goodsQueryVO.getCategoryId());
		}
		
		conditions.put("mark",0);
		
		List<Goods> goodsList = null;
		List<Integer> commentList = null;
		int totalCount;
		try {
			goodsList = goodsService.pageList(page, conditions);
			commentList = new ArrayList<Integer>();
			Map<String, Object> cond = new HashMap<String, Object>();
			if(goodsList.size()>0){
				for (Goods goods : goodsList) {
					cond.put("goodsId", goods.getId());
					int count = commentService.totalCount(cond);
					commentList.add(count);
				}
			}
			totalCount = goodsService.totalCount(conditions);
		} catch (Exception e) {
			logger.error("数据库异常",e);
			result.setErrorMsg("数据库异常");
			result.setResult(false);
			return result.toJson();
		}
		page.setTotalCount(totalCount);
		Map<String,Object> mp = new HashMap<String,Object>();
		mp.put("totalPage",page.getTotalPage());
		mp.put("goodsList", goodsList);
		mp.put("commentList", commentList);
		result.setObj(mp);
		result.setResult(true);
		return result.toJson();
	}

	@RequestMapping(value = "/get.do", method = { RequestMethod.POST,RequestMethod.GET })
	@ResponseBody
	public String get(int id)
			throws UnsupportedEncodingException {
		Result result = new Result();
		Goods goods = null;
		List<Pic> picList = null;
		List<Pic> titlePicList = null;
		Category category = null;
		try {
			goods = goodsService.get(id);
			picList = goodsService.getPicListById(id);
			titlePicList = goodsService.getTitlePicListById(id);
			category = goodsService.getCategoryById(id);
		} catch (Exception e) {
			logger.error("数据库异常...",e);
			result.setErrorMsg("数据库异常...");
			result.setResult(false);
			return result.toJson();
		}
		Map<String,Object> data = new HashMap<String, Object>();
		data.put("goods",goods);
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		try {
			String format = sdf.format(goods.getEndDate());
			data.put("endDate", format);
			if(null != goods.getExpiredDate()){
				String format2 = sdf.format(goods.getExpiredDate());
				data.put("expiredDate", format2);
			}
		} catch (Exception e) {
			logger.error("格式化时间错误,",e);
		}
		data.put("picList",picList);
		data.put("titlePicList",titlePicList);
		data.put("category",category);
		result.setObj(data);
		result.setResult(true);
		return result.toJson();
	}

	@RequestMapping(value = "/getSku.do", method = { RequestMethod.POST,RequestMethod.GET })
	@ResponseBody
	public String getSku(int id)
			throws UnsupportedEncodingException {
		Result result = new Result();
		List<Color> colorList = null;
		List<Size> sizeList = null;
		List<ColorSizeItem> colorSizeItemList = null;
		try {
			colorList = goodsService.getColorListById(id);
			sizeList = goodsService.getSizeListById(id);
			colorSizeItemList = colorSizeItemService.getByGoodsId(id);
		} catch (Exception e) {
			logger.error("数据库异常...",e);
			result.setErrorMsg("数据库异常...");
			result.setResult(false);
			return result.toJson();
		}
		Map<String,Object> data = new HashMap<String, Object>();
		data.put("colorList", colorList);
		data.put("sizeList", sizeList);
		data.put("colorSizeItemList", colorSizeItemList);
		result.setObj(data);
		result.setResult(true);
		return result.toJson();
	}
	
	
	 
	/**
	 * 通过颜色id获取商品颜色尺码对应信息
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping(value = "/getColorSizeItemListByColorId.do", method = {
			RequestMethod.POST, RequestMethod.GET })
	@ResponseBody
	public String getColorSizeItemListByColorId(int colorId)
			throws UnsupportedEncodingException {
		Result result = new Result();
		List<ColorSizeItem> colorSizeItemList = null;
		try {
			colorSizeItemList = goodsService.getColorSizeItemByColorId(colorId);
		} catch (Exception e) {
			logger.error("数据库异常...", e);
			result.setErrorMsg("数据库异常...");
			result.setResult(false);
			return result.toJson();
		}
		result.setObj(colorSizeItemList);
		result.setResult(true);
		return result.toJson();
	}


	/**
	 * 去挑战之前判断用户是否有余额
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping(value = "/judgeMoney.do", method = {RequestMethod.GET })
	@ResponseBody
	public String judgeMoney(int goodsId,HttpSession session){
		Result result = new Result();
		try {
			Customer customerSess = (Customer) session.getAttribute("customer");
			//获取数据库最新
			Customer customer = customerService.get(customerSess.getId());
			Goods goods = goodsService.get(goodsId);
			int gameNum = goods.getGameNum();
			BigDecimal amount = customer.getAmount();
			//已经满足积分购买
			if(customer.getIntegral() >= goods.getIntegral()){
				result.setResult(true);
				result.setErrorCode(3);
				result.setObj(amount.intValue());
				result.setErrorMsg("满足积分购买");
				return result.toJson();
			}
			if(amount.intValue() <gameNum) {
				result.setResult(true);
				result.setErrorCode(2);
				result.setObj(amount.intValue());
				result.setErrorMsg("余额不足");
				return result.toJson();
			}
		} catch (Exception e) {
			logger.error("数据库异常...", e);
			result.setErrorMsg("数据库异常...");
			result.setResult(false);
			return result.toJson();
		}
		result.setResult(true);
		return result.toJson();
	}
	
	/**
	 * 通过尺码id获取商品颜色尺码对应信息
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping(value = "/getColorSizeItemListBySizeId.do", method = {
			RequestMethod.POST, RequestMethod.GET })
	@ResponseBody
	public String getColorSizeItemListBySizeId(int sizeId)
			throws UnsupportedEncodingException {
		Result result = new Result();
		List<ColorSizeItem> colorSizeItemList = null;
		try {
			colorSizeItemList = goodsService.getColorSizeItemBySizeId(sizeId);
		} catch (Exception e) {
			logger.error("数据库异常...", e);
			result.setErrorMsg("数据库异常...");
			result.setResult(false);
			return result.toJson();
		}
		result.setObj(colorSizeItemList);
		result.setResult(true);
		return result.toJson();
	}
	 
}
